<template>
  <div class="drawer">
    <el-drawer v-model="drawerData.visible" :title="drawerData.title" size="35%">
      <el-form class="form_box" ref="formRef" :model="formData" label-width="auto" label-position="right">
        <div class="type_box">
          <div class="type_color"></div>
          <div class="type_text"> 企业信息 </div>
        </div>
        <!-- 动态属性 -->
        <el-form-item :label="item.attr_name" v-for="(item, index) in formData.company_attr" :key="item.attr_id" :prop="`company_attr.${index}.current_val`" :rules="onRules(item)">
          <!-- 区域 -->
          <CascaderItem v-if="item.attr_type == 'pca'" :itemValue="item" />
          <!-- <el-cascader v-if="item.attr_type == 'pca'" v-model="item.current_val" :placeholder="`请选择${item.attr_name}`" :options="CityJson" :props="cityProps" clearable /> -->
          <el-input
            v-if="['textbox', 'mobile', 'email'].includes(item.attr_type)"
            v-model.trim="item.current_val"
            :placeholder="`请输入${item.attr_name}`"
            :maxlength="item.max_length ? item.max_length : item.attr_type == 'mobile' ? 11 : 300"
            :show-word-limit="item.max_length"
            @blur="onGettaxNu(item.current_val, item.system_code)"
            :disabled="item.system_code == 'tax_nu'"
          />
          <!-- 多行文本 -->
          <el-input v-if="item.attr_type == 'textarea'" type="textarea" v-model="item.current_val" :placeholder="`请输入${item.attr_name}`" :rows="5" :maxlength="item.max_length ? item.max_length : 300" :show-word-limit="item.max_length" />
          <!-- 图片 -->
          <div v-if="item.attr_type == 'picture'" class="upload">
            <Upload :url="item.current_val" @submit="(v) => (item.current_val = v)" />
            <span class="upload_desc">支持jpg、png、jpeg、pdf，大小不超过10M </span>
          </div>
          <!-- 选择框 -->
          <el-select v-if="item.attr_type == 'select'" style="width: 100%" v-model="item.current_val" :placeholder="`请选择${item.attr_name}`">
            <el-option v-for="it in item.attr_val" :key="it.val" :label="it.val" :value="it.key"></el-option>
          </el-select>
          <!-- 多选 -->
          <el-checkbox-group v-if="item.attr_type == 'muti_select'" v-model="item.current_val">
            <el-checkbox v-for="it in item.attr_val" :key="it.key" :label="it.key">{{ it.val }}</el-checkbox>
          </el-checkbox-group>
          <!-- 日期 -->
          <el-date-picker v-if="item.attr_type == 'date'" style="width: 100%" value-format="YYYY-MM-DD" v-model="item.current_val" type="date" placeholder="请选择日期"> </el-date-picker>
        </el-form-item>
        <div class="type_box">
          <div class="type_color"></div>
          <div class="type_text"> 客户信息 </div>
        </div>
        <!-- <el-form-item label="线索来源">
          <el-select style="width: 100%" v-model="formData.clue_source_id" placeholder="请选择线索来源">
            <el-option v-for="item in clubSourceOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="客户公海" prop="clue_seas_id" :rules="rules.clue_seas_id">
          <el-select style="width: 100%" v-model="formData.clue_seas_id" placeholder="请选择客户公海">
            <el-option v-for="item in custOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户阶段" prop="clue_stage_id" :rules="rules.clue_stage_id">
          <el-select style="width: 100%" v-model="formData.clue_stage_id" placeholder="请选择客户阶段" @change="onClueStageId">
            <el-option v-for="item in custStageOption" :label="item.name" :value="item.id" :key="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="线索等级" prop="clue_level_id" :rules="rules.clue_level_id">
          <el-select style="width: 100%" v-model="formData.clue_level_id" placeholder="请选择线索等级">
            <el-option v-for="item in custLevelOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="客户来源">
          <el-select style="width: 100%" v-model="formData.clue_source_id" placeholder="请选择客户来源">
            <!-- <el-option v-for="item in custSourceOption" :key="item.id" :label="item.name" :value="item.id"></el-option> -->
            <el-option v-for="item in custSourceOption" :key="item.key" :label="item.val" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属员工" prop="belong_staff" :rules="rules.belong_staff">
          <div class="yuangong-list">
            <div v-for="item in belongStaffList" :key="item.name">
              <img src="@/assets/image/customer/renyuan_icon.png" alt="" />
              <span>{{ item.name }}</span>
              <img @click="changeDepart('belongStaff', item)" class="del_icon" src="@/assets/image/customer/close_icon.png" alt="" />
            </div>
          </div>
          <el-button @click="openDepart('belongStaff')">请选择员工</el-button>
        </el-form-item>
        <el-form-item label="协助员工">
          <div class="yuangong-list">
            <div v-for="item in assistStaffList" :key="item.name">
              <img src="@/assets/image/customer/renyuan_icon.png" alt="" />
              <span>{{ item.name }}</span>
              <img @click="changeDepart('assistStaff', item)" class="del_icon" src="@/assets/image/customer/close_icon.png" alt="" />
            </div>
          </div>
          <el-button @click="openDepart('assistStaff')">请选择员工</el-button>
        </el-form-item>
        <!-- 动态属性 -->
        <el-form-item :label="item.attr_name" v-for="(item, index) in formData.cust_attr" :key="item.attr_id" :prop="`cust_attr.${index}.current_val`" :rules="onRules(item)">
          <!-- 区域 -->
          <CascaderItem v-if="item.attr_type == 'pca'" :itemValue="item" />
          <!-- <el-cascader v-if="item.attr_type == 'pca'" v-model="item.current_val" :placeholder="`请选择${item.attr_name}`" :options="CityJson" :props="cityProps" clearable /> -->

          <el-input v-if="['textbox', 'mobile', 'email'].includes(item.attr_type)" v-model="item.current_val" :placeholder="`请输入${item.attr_name}`" :maxlength="item.attr_type == 'mobile' ? 11 : 300" :show-word-limit="false" />
          <!-- 多行文本 -->
          <el-input v-if="item.attr_type == 'textarea'" type="textarea" v-model="item.current_val" :placeholder="`请输入${item.attr_name}`" :rows="5" />
          <!-- 图片 -->
          <div v-if="item.attr_type == 'picture'" class="upload">
            <Upload :url="item.current_val" @submit="(v) => (item.current_val = v)" />
            <span class="upload_desc">支持jpg、png、jpeg大小不超过10M </span>
          </div>
          <!-- 选择框 -->
          <el-select v-if="item.attr_type == 'select'" style="width: 100%" v-model="item.current_val" :placeholder="`请选择${item.attr_name}`">
            <el-option v-for="it in item.attr_val" :key="it.val" :label="it.val" :value="it.key"></el-option>
          </el-select>
          <!-- 多选 -->
          <el-checkbox-group v-if="item.attr_type == 'muti_select'" v-model="item.current_val">
            <el-checkbox v-for="it in item.attr_val" :key="it.key" :label="it.key">{{ it.val }}</el-checkbox>
          </el-checkbox-group>
          <!-- 日期 -->
          <el-date-picker v-if="item.attr_type == 'date'" style="width: 100%" value-format="YYYY-MM-DD" v-model="item.current_val" type="date" placeholder="请选择日期"> </el-date-picker>
        </el-form-item>
        <div class="type_box">
          <div class="type_color"></div>
          <div class="type_text"> 联系人信息 </div>
        </div>
        <div class="card" v-for="(item, index) in formData.company_contacts" :key="index">
          <div class="card_header">
            <div class="card_name">联系人{{ index + 1 }}</div>
            <el-icon v-if="index > 0" @click="onDeleteContacts(index)" class="card_delete"><Delete /></el-icon>
          </div>
          <el-form-item class="contacts_item" label="姓名" :prop="`company_contacts.${index}.name`" :rules="rules.name" label-width="70">
            <template #label>
              <span style="padding-right: 14px">姓名</span>
            </template>
            <el-input class="contacts_input" v-model="item.name" placeholder="请输入客户名称" />
          </el-form-item>
          <el-form-item class="contacts_item" label="手机号" :prop="`company_contacts.${index}.mobile`" :rules="rules.mobile" label-width="70">
            <el-input class="contacts_input" v-model="item.mobile" placeholder="请输入手机号" maxlength="11" />
          </el-form-item>
        </div>
        <el-button v-if="formData.company_contacts?.length < 5" plain @click="onAddContacts">添加联系人</el-button>
      </el-form>
      <template #footer>
        <el-button @click="onRest">重置</el-button>
        <el-button type="primary" @click="onSubmit">转为客户</el-button>
      </template>
    </el-drawer>
  </div>
  <ZWDepart ref="DepartRef" @submit="getDepart" />
</template>

<script lang="ts" setup>
  import Upload from './Upload.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import Dialog from '@/components/Dialog.vue'
  import CityJson from '@/assets/js/city.js'
  import { getTaxNumber } from '@/api/common'
  import { getClubSource } from '@/api/customer/clubManage/commonSea'
  import { stageList } from '@/api/customerCenter/labellagroup'
  import { seaList, applyCompanyHelper, getCompanyCustomerForm, getCompanyCustomerDetail, addCompanyCustomer, aditCompanyCustomer } from '@/api/customerCenter/customerSea'
  import { cpCnpre, saveCn } from '@/api/employe/employeetasks/taskmanage'
  import { getClueApplyCorpForm, getClueList, getClueLevelList, getClubSourceList, clueCompanyCreate, getClueCompanyInfo, clueCompanyEdit } from '@/api/customer/clubManage/clubSea'
  import { getSetionId } from '@/utils/utils'
  import { ElMessage } from 'element-plus'
  import { ref, reactive, watch, nextTick } from 'vue'
  import CascaderItem from '@/components/customerCenter/CascaderItem.vue'

  const emit = defineEmits(['submit', 'toggle'])
  const formRef = ref<any>(null)
  const drawerData = ref({
    visible: false,
    title: '转化为企业客户',
    direction: 'rtl', //从右往左打开
    id: '', //查看
    clue_seas_id: '' //查看
  })

  const formData: any = ref({
    id: '', //线索ID
    clue_stage_id: '', //线索阶段ID
    company_attr: [],
    clue_seas_id: '',
    clue_level_id: '',
    clue_source_id: '',
    belong_staff: '',
    assist_staff: [],
    cust_attr: [],
    company_contacts: [
      {
        name: '',
        mobile: ''
      }
    ],
    mobile: '',
    corp_name: ''
  })
  const onClueStageId = (val: any) => {
    console.log('选择客户阶段', val)

    formData.value.clue_level_id = val
  }
  const taxNuIndex = ref(-1) // 是否开启企业税号
  const onGettaxNu = (v: any, type: any) => {
    console.log(v, type, '企业税号')
    if (type == 'corp_name' && v && taxNuIndex.value != -1) {
      getTaxNumber({ keyword: v })
        .then((res: any) => {
          console.log('企业税号', res.credit_code)
          formData.value.company_attr[taxNuIndex.value].current_val = res.credit_code
        })
        .catch((err: any) => {
          formData.value.company_attr[taxNuIndex.value].current_val = ''
        })
    }
  }
  let validmobile = (rules: any, value: any, callback: any) => {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (value && !rex.test(value)) {
      callback(new Error('请输入正确的11位手机号码'))
    } else {
      callback()
    }
  }
  // 当前输入框有值才校验
  const validEmail = (rule: any, value: any, callback: any) => {
    let rex = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
    if (value && !rex.test(value)) {
      callback(new Error('请输入正确的邮箱'))
    } else {
      callback()
    }
  }
  // 重置
  const onRest = () => {
    console.log('重置')
    formRef.value?.resetFields()
  }
  const onAddContacts = () => {
    formData.value.company_contacts.push({ name: '', mobile: '' })
  }
  const onDeleteContacts = (index: number) => {
    formData.value.company_contacts.splice(index, 1)
  }
  const onSubmit = () => {
    formRef.value.validate((valid: any, fields: any) => {
      if (valid) {
        formData.value.company_attr.forEach((item: any, index: any) => {
          if (item.system_code == 'corp_name') {
            formData.value.corp_name = item.current_val
          }
        })
        formData.value.cust_attr.forEach((item: any, index: any) => {
          if (item.system_code == 'mobile') {
            formData.value.mobile = item.current_val
          }
        })
        saveCn(formData.value).then((res: any) => {
          ElMessage.success('转化成企业客户成功')
          emit('submit')
          drawerData.value.visible = false
        })
      } else {
        console.log('error ', fields)
        ElMessage.warning(Object.values(fields)[0][0].message)
      }
    })
  }
  const rules = ref<any>({
    name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    mobile: [
      { required: true, message: '请输入手机号', trigger: 'change' },
      { validator: validmobile, trigger: 'blur' }
    ],
    clue_seas_id: [{ required: true, message: '请选择客户公海', trigger: 'blur' }],
    clue_stage_id: [{ required: true, message: '请选择客户阶段', trigger: 'blur' }],
    clue_level_id: [{ required: true, message: '请选择客户等级', trigger: 'blur' }],
    clue_source_id: [{ required: true, message: '请选择客户来源', trigger: 'blur' }],
    belong_staff: [{ required: true, message: '请选择归属员工', trigger: 'blur' }],
    assist_staff: [{ required: true, message: '请选择协助员工', trigger: 'blur' }]
  })
  const onRules = (item: any) => {
    const required = item.is_required == 2
    let obj = {
      pca: [{ required, message: '请输入区域地址', trigger: 'blur' }],
      picture: [{ required, message: '请上传营业执照', trigger: 'blur' }],
      mobile: [
        { required, message: `请输入${item.attr_name}`, trigger: 'change' },
        { required, validator: validmobile, trigger: 'blur' }
      ],
      email: [
        { required, message: '请输入邮箱', trigger: 'change' },
        { required, validator: validEmail, trigger: 'blur' }
      ],
      muti_select: [{ required, message: `请选择${item.attr_name}`, trigger: 'change' }],
      select: [{ required, message: `请选择${item.attr_name}`, trigger: 'change' }],
      textbox: [{ required, message: `请输入${item.attr_name}`, trigger: 'blur' }],
      textarea: [{ required, message: `请输入${item.attr_name}`, trigger: 'blur' }]
    }
    return obj[item.attr_type]
  }

  // 选择员工
  const belongStaffList = ref<any>([])
  const assistStaffList = ref<any>([])
  const DepartRef = ref<any>(null)
  const DepartRefType = ref('')
  const openDepart = (type?: any) => {
    DepartRefType.value = type
    if (type == 'belongStaff') {
      DepartRef.value.multiple = false
      DepartRef.value.selectedMember = [...belongStaffList.value]
      DepartRef.value.disabledSelected = [...formData.value.assist_staff]
    } else {
      DepartRef.value.multiple = true
      DepartRef.value.selectedMember = [...assistStaffList.value]
      DepartRef.value.disabledSelected = [formData.value.belong_staff]
    }
    DepartRef.value.departVisble = true
  }
  const getDepart = (res: any) => {
    if (DepartRefType.value == 'belongStaff') {
      belongStaffList.value = res
      formData.value.belong_staff = res[0].id
    } else {
      assistStaffList.value = res
      formData.value.assist_staff = getSetionId('id', assistStaffList.value)
    }
    DepartRef.value.departVisble = false
  }
  const changeDepart = (type: any, data: any) => {
    if (type == 'belongStaff') {
      belongStaffList.value = []
      formData.value.belong_staff = ''
    } else {
      assistStaffList.value = assistStaffList.value.filter((item: any) => item.id != data.id)
      formData.value.assist_staff = getSetionId('id', assistStaffList.value)
    }
  }
  const clubSourceOption = ref<any>([]) //获取线索来源列表
  const custOption = ref<any>([]) //获取公海列表
  const custLevelOption = ref<any>([]) //获取线索等级列表
  const custSourceOption = ref<any>([]) //获取客户来源列表
  const custStageOption = ref<any>([]) //获取客户阶段字典
  const getFomr = () => {
    Promise.all([
      cpCnpre({ id: drawerData.value.id }),
      seaList({ page: 1, page_size: 1000, name: '' }),
      getClueLevelList({ page: 1, page_size: 999 }),
      getClubSource({ page: 1, page_size: 999 }),
      getClubSourceList({ page: 1, page_size: 999 }),
      stageList({ page: 1, page_size: 99999 })
    ]).then((res: any) => {
      console.log('基础数据', res)
      custOption.value = res[1].data
      custLevelOption.value = res[2].data
      custSourceOption.value = res[3].data.filter((item: any) => item.status == 1).map((item: any) => ({ key: item.id, val: item.name }))
      console.log('客户来源列表', custSourceOption.value)

      clubSourceOption.value = res[4]
      custStageOption.value = res[5] || []
      const cust_attr = res[0].cust_attr.map((item: any, index: any) => {
        if (item.attr_type != 'pca') {
          item.current_val = ''
        }
        if (item.attr_type == 'muti_select') {
          item.current_val = []
        }
        if (item.attr_type == 'select') {
          item.current_val = ''
        }
        if (item.system_code == 'source') {
          item.attr_val = custSourceOption.value
        }
        if (item.attr_type == 'pca') {
          if (item.current_val) {
            item.attr_val = [item.current_val.province_code.toString(), item.current_val.city_code.toString(), item.current_val?.area_code?.toString()]
            if (item.attr_val[2] == 0) {
              item.attr_val.pop()
            }
          }
        }
        return item
      })
      const company_attr = res[0].company_attr.map((item: any, index: any) => {
        if (item.system_code == 'tax_nu') {
          console.log('企业税号索引', index)
          taxNuIndex.value = index
        }
        !!item.current_val || (item.current_val = '')
        if (item.attr_type == 'muti_select') {
          item.current_val = []
        }
        if (item.attr_type == 'select') {
          item.current_val = ''
        }
        if (item.attr_type == 'pca') {
          if (item.current_val) {
            item.attr_val = [item.current_val.province_code.toString(), item.current_val.city_code.toString(), item.current_val?.area_code?.toString()]
            if (item.attr_val[2] == 0) {
              item.attr_val.pop()
            }
          }
        }
        return item
      })
      console.log('客户来源', custSourceOption.value)
      formData.value = res[0]
      formData.value.clue_level_id = ''
      formData.value.clue_source_id = ''
      formData.value.cust_attr = cust_attr
      formData.value.company_attr = company_attr
      formData.value.id = drawerData.value.id
      formData.value.clue_seas_id = drawerData.value.clue_seas_id
    })
  }
  watch(
    () => drawerData.value.visible,
    (v: any) => {
      if (v) {
        getFomr()
      } else {
        onRest()
        drawerData.value = {
          visible: false,
          title: '转化为企业客户',
          direction: 'rtl', //从右往左打开
          id: '', //查看
          clue_seas_id: '' //查看
        }
      }
    }
  )
  defineExpose({
    drawerData
  })
</script>

<style lang="scss" scoped>
  .form_box {
    padding-top: 20px;
    padding-bottom: 60px;
  }

  .upload-content {
    &.noEdit {
      pointer-events: none !important;

      .upload-box {
        background: lightgray;
        position: relative;
        &::after {
          content: '';
          width: 100%;
          height: 100%;
          background: lightgray;
          opacity: 0.6;
          position: absolute;
          top: 0;
          left: 0;
        }
      }
    }
    .upload-box {
      width: 110px;
      height: 110px;
      text-align: center;
      border-radius: 4px;
      background: #f8f8f8;
      border: 1px solid #eaeaea;
      box-sizing: border-box;
      padding-top: 28px;
      img {
        width: 20px;
        height: 20px;
      }
      div {
        width: 100%;
        line-height: 14px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #ff6b00;
      }
    }
    .upload-file-box {
      position: relative;
      width: 110px;
      height: 110px;
      border-radius: 4px;
      border: 1px solid #eaeaea;
      overflow: hidden;
      .del {
        position: absolute;
        width: 15px;
        height: 15px;
        top: 5px;
        right: 5px;
        color: #e4e7ed;
      }
    }
    .upload-desc {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #969696;
      padding-top: 10px;
      span {
        color: #ff6b00;
        cursor: pointer;
      }
    }
  }
  .customer_type {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
    font-size: 14px;
    font-family: STHeitiSC-Light, STHeitiSC;
    color: #33302d;
    .customer_type_left {
      .clue_type {
        margin-left: 3px;
      }
    }
    .customer_type_right {
      display: flex;
      align-items: center;
      cursor: pointer;
      color: #ff6b00;
      .icon_type {
        transform: rotate(90deg);
      }
    }
  }
  .type_box {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    .type_color {
      width: 4px;
      height: 16px;
      margin-right: 6px;
      background: #ff6b00;
    }
    .type_text {
      font-size: 14px;
      font-weight: 500;
      color: #33302d;
    }
  }
  .card {
    width: 350px;
    padding: 16px 24px 10px;
    margin-bottom: 18px;
    background: #ffffff;
    border: 1px solid #eaeaea;
    .card_header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    .card_name {
      font-size: 14px;
      color: #33302d;
    }
    .card_delete {
      cursor: pointer;
    }
    .contacts_item {
      border-bottom: 1px solid #eaeaea;

      :deep(.el-input) {
        .el-input__wrapper {
          padding: 0;
          box-shadow: none;
          box-sizing: border-box;
        }
      }
    }
    .contacts_input :deep(.el-input__inner) {
      border: none;
      padding-left: 0;
      border-radius: 0;
    }
  }
  .clue_type {
    margin-bottom: 0;
  }
  .upload {
    position: relative;
    .upload_desc {
      margin-left: 10px;
      position: absolute;
      left: 110px;
      bottom: -10px;
      font-size: 12px;
      font-family: STHeitiSC-Light, STHeitiSC;
      color: #969696;
      vertical-align: bottom;
    }
  }
  .appdialog_desc {
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .yuangong-list {
    div {
      display: inline-block;
      vertical-align: middle;
      background: #fffaf9;
      border-radius: 1px;
      margin-right: 10px;
      margin-bottom: 10px;
      padding: 4px 8px;
      line-height: 22px;
      box-sizing: border-box;
      img {
        width: 10px;
        height: 12px;
      }
      .del_icon {
        width: 12px;
        height: 12px;
        cursor: pointer;
      }
      span {
        margin: 0 10px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #35383a;
      }
    }
  }
</style>
